package com.woniu.interceptor;

import com.alibaba.fastjson.JSON;
import com.woniu.annotation.PreAuthorize;
import com.woniu.mapper.AuthMapper;
import com.woniu.util.ResponseEnum;
import com.woniu.util.ResponseUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Resource
    private AuthMapper mapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        System.out.println("拦截器执行了");
        if (handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            //获得方法
            Method method = handlerMethod.getMethod();
            //有注解的方法
            PreAuthorize annotation = method.getAnnotation(PreAuthorize.class);
            if (annotation != null){
                String[] value = annotation.value();

                List<String> auth = mapper.queryAuthByUserId(1);

                boolean flag = Arrays.stream(value).allMatch(e -> auth.contains(e));
                if (!flag){
                    response.setContentType("application/json;charset=utf-8");
                    response.getWriter().write(JSON.toJSONString(ResponseUtil.get(ResponseEnum.AUTH)));
                    System.out.println("不放行");
                    return false;
                }
            }
        }
        return true;//放行
    }
}
